import "./styles.css";
import "antd/dist/antd.css";
import type { callBackType, JoLPlayerRef } from "jol-player";
import JoLPlayer from "jol-player";
// @ts-ignore
import React, { useRef, useEffect, useState } from "react";
interface customProps {
  fileUrl: string;
  planId?: any;
  logId?: any;
}
const VideoPlayForm: React.FC<customProps> = (props) => {
  const [alertAction, setAlertAction] = useState<boolean>(true)

  // 提示语
  if (alertAction){
    alert("注意：\n" +
      "1，仅在培训完成的7天内观看培训视频才可以获得积分！\n" +
      "2，需要获取积分的，播放中途请勿刷新页面，否则会重置观看时长！\n" +
      "3，未参加线下培训，需要参加线上培训的，请勿调整视频倍速，以免观看时长不够，无法获得积分！"
    )
    setAlertAction(false)
  }

  // 通知后端，状态更新
  // TOKEN
  let token = localStorage.getItem('token');

  function NoticeBackend(values: any) {
    fetch('/api/px/readLog?logId=' + props.logId, {
      method: 'POST',
      body: JSON.stringify((values)),
      headers:{
        'Authorization': `Bearer ${token}`
      }
    }).then(res=>res.json()).then(res => {
      if (res){
        console.log(res)
      }
    })
  }

  // 定时任务通知后端，视频持续
  setInterval(()=>{
    if (props.logId != 0){
      NoticeBackend({"keepAlive": true})
    }

  }, 5000)

  // 视频播放钩子
  const videoRef = useRef<JoLPlayerRef>(null!);
  const onEndEd: callBackType = (val) => {
    // 视频播放结束，给后台发送播放结束的标志，并通过后台判断合计播放时间
    // 如果合计播放时间大于总时长的80%，则弹出评价窗口
    // 评价后后台自动计算积分
    console.log(`onEndEd`, val);
  };
  const onPause: callBackType = (val) => {

    // 通知服务器，本次播放暂停
    if (props.logId != 0) {
      NoticeBackend({duration: val.duration, is_play: "pause"})
    }
  };
  const onPlay: callBackType = (val) => {

    // 通知服务器，本次播放暂停
    if (props.logId != 0) {
      NoticeBackend({"duration": val.duration, is_play: "play"})
    }
  };
  const onTimeChange: callBackType = (val) => {
    // console.log(`onTimeChange`, val);
  };
  const onError = () => {
    console.log(`onError`);
  };
  useEffect(() => {
    console.log(`videoRef.current`, videoRef.current);
  }, [videoRef.current]);

  // 当页面被最小化时，暂停
  //离开页面时，暂停
  // 监听 visibility change 事件
  document.addEventListener('visibilitychange', function() {
      // 页面变为不可见时触发
      if (document.visibilityState === 'hidden') {
        videoRef.current?.pause()
      }
      // 页面变为可见时触发
      if (document.visibilityState === 'visible') {
        videoRef.current?.play()
      }
    }
  );
  // 计算屏幕高度
  const {innerWidth, innerHeight} = window;
  const w = innerWidth;
  const h = innerHeight;
  return (
    <div className="App">
      <JoLPlayer
        ref={videoRef}
        onEndEd={onEndEd}
        onPause={onPause}
        onPlay={onPlay}
        onTimeChange={onTimeChange}
        onError={onError}
        option={{
          videoSrc: props.fileUrl,
          pausePlacement: "center",
          theme: "#ffb821",
          width: w,
          height: h,
          isShowMultiple: true,
          language: "zh",
          mode: "heightFix",
        }}
      />
    </div>
  );
}
export default VideoPlayForm;
